package ge.telasi.tasks.ui.structure;

import ge.telasi.tasks.LocaleManager;
import ge.telasi.tasks.model.Structure;
import ge.telasi.tasks.ui.Platform;
import ge.telasi.tasks.ui.comp.StructurableTreeModel;
import ge.telasi.tasks.ui.UIUtils;
import java.awt.Component;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import static ge.telasi.tasks.ui.log.LoggerUtils.manageException;
import static ge.telasi.tasks.ui.UIUtils.askConfirmation;

/**
 * @author dimitri
 */
public class StructureTreePanel extends JPanel {
    static List<Structure> CACHED_DATA;

    /** Creates new form StructureListPanel */
    public StructureTreePanel() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tree = new javax.swing.JTree();

        tree.setModel(new StructureTreeModel(null));
        tree.setCellRenderer(new StructureRenderer());
        jScrollPane1.setViewportView(tree);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree tree;
    // End of variables declaration//GEN-END:variables

    public boolean refreshFast(JComponent parentComp) {
        if (CACHED_DATA == null) {
            return refresh(parentComp);
        } else {
            tree.setModel(new StructureTreeModel(CACHED_DATA));
            return true;
        }
    }

    public boolean refresh(JComponent parentComp) {
        try {
            Platform pl = Platform.getDefault();
            List<Structure> structures = pl.getFacade().getRootStructures();
            CACHED_DATA = structures;
            tree.setModel(new StructureTreeModel(structures));
            return true;
        } catch (Exception ex) {
            manageException(this, ex);
            return false;
        }
    }

    public void newStructure(JComponent parentComp) {
        StructureDialog dialog = new StructureDialog(this);
        dialog.setParentStructure(getSelecedStructure());
        UIUtils.openDialog(dialog);
        if (dialog.isApproved()) {
            StructureTreeModel model = (StructureTreeModel) tree.getModel();
            model.insert(dialog.getStructure());
        }
    }

    public void editStructure(JComponent parentComp) {
        Structure structure = getSelecedStructure();
        if (structure != null) {
            StructureDialog dialog = new StructureDialog(this);
            dialog.setStructure(structure);
            UIUtils.openDialog(dialog);
            if (dialog.isApproved()) {
                StructureTreeModel model = (StructureTreeModel) tree.getModel();
                model.replace(structure, dialog.getStructure());
            }
        }
    }

    public void deleteStructure(JComponent parentComp) {
        Structure structure = getSelecedStructure();
        if (structure != null) {
            Platform pl = Platform.getDefault();
            LocaleManager lm = pl.getLocaleManager();
            String msg = lm.getMessage("General.deleteMsg", structure.getName());
            if (askConfirmation(parentComp, msg)) {
                try {
                    pl.getFacade().deleteStructure(pl.getCredentials(), structure);
                    StructureTreeModel model = (StructureTreeModel) tree.getModel();
                    model.remove(structure);
                } catch (Exception ex) {
                    manageException(this, ex);
                }
            }
        }
    }

    public Structure getSelecedStructure() {
        TreePath path = tree.getSelectionPath();
        if (path != null) {
            Object last = path.getLastPathComponent();
            if (last instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) last;
                if (node.getUserObject() instanceof Structure) {
                    return (Structure) node.getUserObject();
                }
            }
        }
        return null;
    }

    public void selectStructure(Structure structure) {
        StructureTreeModel model = (StructureTreeModel) tree.getModel();
        TreePath path = model.path(structure);
        if (path != null) {
            tree.expandPath(path);
            tree.setSelectionPath(path);
        } else {
            tree.setSelectionRow(0);
        }
    }

    public JTree getTree() {
        return tree;
    }

    class StructureTreeModel extends StructurableTreeModel<Structure> {
        public StructureTreeModel(List<Structure> firstLevel) {
            super(firstLevel, "სს თელასის სტრუქტურული ერთეულები");
        }
    }

    class StructureRenderer extends DefaultTreeCellRenderer {

        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
            if (node.getUserObject() instanceof String) {
                setIcon(new ImageIcon(getClass().getResource("/ge/telasi/resorces/icons16x16/world.png")));
            } else {
                Structure structure = (Structure) node.getUserObject();
                setIcon(StructureUtils.getIcon(structure.getType()));
                setText(structure.getName());
            }
            return this;
        }

    }

}
